#include "ShareMemory_StringArray.h"

ShareMemory_StringArray* ShareMemory_StringArray::Create(HANDLE& hMap,const std::wstring& name)
{
	SECURITY_ATTRIBUTES sec_attr = { sizeof(sec_attr), nullptr, TRUE };
	hMap = ::CreateFileMapping(
		INVALID_HANDLE_VALUE,
		&sec_attr,
		PAGE_READWRITE,
		0,
		bufferSize * sizeof(wchar_t),
		(LPCWSTR)name.c_str());

	if (hMap == NULL)
		return nullptr;

	auto pBuffer = (LPWSTR)::MapViewOfFile(hMap, FILE_MAP_WRITE, 0, 0, 0);
	if (pBuffer == nullptr)
	{
		CloseHandle(hMap);
		return nullptr;
	}
	auto ptr = new ShareMemory_StringArray(pBuffer);
	ptr->clear();
	return ptr;
}

ShareMemory_StringArray* ShareMemory_StringArray::Open(HANDLE& hMap, const std::wstring& name)
{
	hMap = ::OpenFileMapping(FILE_MAP_ALL_ACCESS, 0, (LPCWSTR)name.c_str());
	if (hMap == NULL)
		return nullptr;

	auto pBuffer = (LPWSTR)::MapViewOfFile(hMap, FILE_MAP_ALL_ACCESS, 0, 0, 0);
	return new ShareMemory_StringArray(pBuffer);
}

void ShareMemory_StringArray::Close(ShareMemory_StringArray* obj, HANDLE hMap)
{
	delete obj;
	::CloseHandle(hMap);
}

int ShareMemory_StringArray::insert(const std::wstring& str)
{
	size_t offset = 0;
	int index = 0;
	std::wstring temp = std::wstring(m_buffer);

	while (temp.length() > 0)
	{
		offset += temp.length() + 1;
		temp = std::wstring(m_buffer + offset);
		index++;
	};

	wcscpy_s(m_buffer + offset, bufferSize - offset, str.c_str());
	wcscpy_s(m_buffer + offset + str.length() + 1, bufferSize - offset - str.length() - 1, ArrayEnd.c_str());
	return index;
}

void ShareMemory_StringArray::clear()
{
	wcscpy_s(m_buffer, bufferSize, ArrayEnd.c_str());
}

int ShareMemory_StringArray::getStringVector(std::vector<std::wstring>& strVec)
{
	size_t offset = 0;
	int index = 0;
	std::wstring temp = std::wstring(m_buffer);

	while (temp.length() > 0)
	{
		strVec.push_back(temp);
		offset += temp.length() + 1;
		temp = std::wstring(m_buffer + offset);
		index++;
	};
	return index;
}
